<?php

namespace app\api\controller;

use app\api\model\ChickenCards as ChickenCards;
use app\api\model\Wallets as Wallets;
use app\api\model\UserUseCards as UserUseCards;
use app\api\model\GiftEggs as GiftEggs;
use app\api\model\User as UserDB;
use app\api\model\AdminConfigs as AdminConfigsDB;


use app\api\model\Cards as CardsDB;
use app\api\model\Yue as YueDB;
use app\api\model\Eggs as EggsDB;


use Illuminate\Support\Carbon;
use support\Request;
use app\traits\OpChickenCard;
use app\traits\CommonScript;

class WalletsController
{

    use OpChickenCard;
    use CommonScript;

    //查询当前用户钱包信息
    public function info(Request $request)
    {
        //获取用户id
        $uid = $request->uid;
        $res = Wallets::where('wallet_user_id', $uid)->first();
        return json([
            'code' => 2,
            'msg' => '获取成功！',
            'data' => $res,
        ]);
    }

    /**
     * @param Request $request
     * @param Wallets $DB
     * @return \support\Response
     * 购买母鸡卡
     */
    public function buyCards(Request $request, Wallets $DB)
    {
        //获取用户id
        $uid = $request->uid;
        //购买个数
        $card_count = $request->post('card_count');
        //实时汇率
        $exchange_rate = $request->post('exchange_rate');
        //交易密码
        $trade_password = $request->post('trade_password');
        $trade_password_db = UserDB::where('uid', $uid)->value('trade_password');
        //校验密码
        if (!$this->verifyTradePwd($trade_password, $trade_password_db)) {
            return json([
                'code' => 0,
                'msg' => '交易密码错误！',
                'data' => '',
            ]);
        }
        //余额校验
        $cost = $card_count * $exchange_rate;
        $cash_db = Wallets::where('wallet_user_id', $uid)->value('cash');
        $cash_new = $cash_db - $cost;
        if ($cash_new < 0) {
            return json([
                'code' => 0,
                'msg' => '余额不足！',
                'data' => '',
            ]);
        }
        //去减掉库存
        $total_cards = ChickenCards::where('id', '2')->value('total_cards');
        $card_price = ChickenCards::where('id', '2')->value('card_price');
        $new_total_cards = $total_cards - $card_count;
        if ($new_total_cards < 0) {
            return json([
                'code' => 0,
                'msg' => '已售空!',
                'data' => '',
            ]);
        }
        Wallets::where('wallet_user_id', $uid)->sharedLock()->update([
            'cash' => $cash_new,
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);
        //抽到的每张卡
        $cards_list = $this->randomPushCards($card_count);
        //购买记录表中添加购买记录
        $cards = $this->setCardsList($cards_list);
        $query = $DB->where('wallet_user_id', $uid);
        $new_cards = [];
        foreach ($cards as $k => $v) {
            $base_count = $query->value($k);
            $new_cards[$k] = $v + $base_count;
        }
        $buy_cards_num_db= Wallets::where('wallet_user_id', $uid)->value('buy_cards_num');
        //给用户钱包加上卡片
        $DB->where('wallet_user_id', $uid)->sharedLock()->update($new_cards);
        $DB->where('wallet_user_id', $uid)->sharedLock()->update([
            'buy_cards_num' => $buy_cards_num_db + $card_count,
        ]);
        ChickenCards::where('id', '2')->sharedLock()->update([
            'total_cards' => $new_total_cards,
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);
        //添加余额记录
        YueDB::insertGetId([
            'uid' => $uid,
            'count' => $cost,
            'type' => '购买卡片',
            'yu_e' => $cash_new,
            'created_at' => Carbon::now()->toDateTimeString()
        ]);
        //添加卡片记录

        CardsDB::insertGetId([
            'uid' => $uid,
            'card' => json_encode($cards),
            'count' => $card_count,
            'type' => '余额购买',
            'yu_e' => $this->cardsYue($uid),
            'created_at' => Carbon::now()->toDateTimeString()
        ]);

        //判断是否是新用户
        $is_new = UserDB::where('uid', $uid)->value('is_new');
        $new_reward = AdminConfigsDB::where('id', '2')->value('new_reward');
        if($is_new==1&&$new_reward==1){
            $add_count =  rand(0, 99) / 100;
            //更新钱包U蛋
            $eggs_db = Wallets::where('wallet_user_id', $uid)->value('held_eggs');
            Wallets::where('wallet_user_id', $uid)->sharedLock()->update([
                'held_eggs' => $add_count +$eggs_db,
            ]);
            UserDB::where('uid', $uid)->sharedLock()->update([
                'is_new' => 0,
            ]);
            //添加U蛋记录
            EggsDB::insertGetId([
                'uid' => $uid,
                'count' => $add_count,
                'type' => '新用户赠送',
                'yu_e' => $add_count +$eggs_db,
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
        }
        return json([
            'code' => 2,
            'msg' => '购买成功！',
            'data' => $cards,
        ]);
    }






    /**
     * @param Request $request
     * @return \support\Response
     * 提取U蛋
     */
    public function useProducedEggs(Request $request)
    {
        //获取用户id
        $uid = $request->uid;
        $count = $request->post('count');
        //交易密码
        $trade_password = $request->post('trade_password');
        $trade_password_db = UserDB::where('uid', $uid)->value('trade_password');
        //校验密码
        if (!$this->verifyTradePwd($trade_password, $trade_password_db)) {
            return json([
                'code' => 0,
                'msg' => '交易密码错误！',
                'data' => '',
            ]);
        }
        $held_eggs = Wallets::where('wallet_user_id', $uid)->value('held_eggs');
        //可取出的U蛋 记录中已经产生-已取出+利息产生的
        $yiyou_eggs = UserUseCards::where('user_id', $uid)->sum('done_eggs');
        $yiqu_eggs = Wallets::where('wallet_user_id', $uid)->value('quchu_eggs');
        $lixi_eggs = Wallets::where('wallet_user_id', $uid)->value('interest_eggs');
        $kqc_eggs = $yiyou_eggs - $yiqu_eggs + $lixi_eggs;
        if ($count > $kqc_eggs) {
            return json([
                'code' => 0,
                'msg' => '提取U蛋不足！',
                'data' => '',
            ]);
        }
        //添加U蛋记录
        EggsDB::insertGetId([
            'uid' => $uid,
            'count' => $count,
            'type' => '孵化器提取',
            'yu_e' => $held_eggs + $count,
            'created_at' => Carbon::now()->toDateTimeString()
        ]);
        //减去钱包数据
        $res = Wallets::where('wallet_user_id', $uid)->update([
            "held_eggs" => $held_eggs + $count,
            "quchu_eggs" => $yiqu_eggs + $count,
            "updated_at" => Carbon::now()->toDateTimeString()
        ]);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    /**
     * 使用母鸡卡
     */
    function useCard(Request $request)
    {
        $req = $request->post();
        $card = array_keys($req)[0];
        $count = array_values($req)[0];
        //获取用户id
        $uid = $request->uid;
        //交易密码
        $trade_password = array_values($req)[1];
        $trade_password_db = UserDB::where('uid', $uid)->value('trade_password');
        //校验密码
        if (!$this->verifyTradePwd($trade_password, $trade_password_db)) {
            return json([
                'code' => 0,
                'msg' => '交易密码错误！',
                'data' => '',
            ]);
        }
        //查询当前账号是否有卡
        $card_db = Wallets::where('wallet_user_id', $uid)->value($card);
        $used_cards = Wallets::where('wallet_user_id', $uid)->value('used_cards');
        if ($card_db < $count) {
            return json(['code' => 4, 'msg' => '没有卡片', 'data' => '']);
        } else {
            //对应卡片数量
            $card_new = $card_db - $count;
            //U蛋数量，原有U蛋+直接得到的U蛋
            $eggs_new = Wallets::where('wallet_user_id', $uid)->value('held_eggs')
                + ChickenCards::where('id', 2)->value('eggs_directly_get') * $count;
            //单次持续生成的U蛋总和
            $all_eggs = (ChickenCards::where('id', 2)->value('eggs_per_card')
                    - ChickenCards::where('id', 2)->value('eggs_directly_get')) * $count;
            //直接获取的U蛋数
            $get_eggs = ChickenCards::where('id', 2)->value('eggs_directly_get') * $count;
            //每天得到的U蛋数
            $settingDay = ChickenCards::where('id', 2)->value('setting_day');
            $math = $all_eggs / $settingDay;
            $every_day_eggs =  round($math, 2,-1);
            //添加卡片使用记录
            UserUseCards::sharedLock()->insertGetId(
                [
                    'user_id' => $uid,
                    'card' => $card,   //使用的卡类型
                    'all_eggs' => $all_eggs,    //使用后一共会得到的U蛋
                    'done_eggs' => 0,      //已经产出的U蛋
                    'card_count' => $count, //卡片数量
                    'days' => 0,   //天数
                    'every_day_eggs' => $every_day_eggs,  //每天产出的U蛋
                    'get_eggs' => $get_eggs,     //直接得到的U蛋
                    'created_at' => Carbon::now()->toDateTimeString()
                ]
            );
            //更新钱包卡片、U蛋
            Wallets::where('wallet_user_id', $uid)->sharedLock()->update([
                $card => $card_new,
                'held_eggs' => $eggs_new,
                'used_cards' => $count + $used_cards,
            ]);

            //添加卡片记录
            CardsDB::insertGetId([
                'uid' => $uid,
                'card' => json_encode($card),
                'count' => $count,
                'type' => '使用卡片',
                'yu_e' => $this->cardsYue($uid),
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
            //添加U蛋记录
            EggsDB::insertGetId([
                'uid' => $uid,
                'count' => $get_eggs,
                'type' => '使用卡片直接获取',
                'yu_e' => $eggs_new,
                'created_at' => Carbon::now()->toDateTimeString()
            ]);

            $res = Wallets::where('wallet_user_id', $uid)->first();
            return json([
                'code' => 2,
                'msg' => '使用成功！',
                'data' => $res,
            ]);
        }

    }

    /***
     *合成卡片
     */
    function compositeCard(Request $request)
    {
        $album_type = $request->post('album_type');
        $need_cards = $this->album_type_card($album_type);
        //获取账户钱包信息
        $uid = $request->uid;
        //交易密码
        $trade_password = $request->post('trade_password');
        $trade_password_db = UserDB::where('uid', $uid)->value('trade_password');
        //校验密码
        if (!$this->verifyTradePwd($trade_password, $trade_password_db)) {
            return json([
                'code' => 0,
                'msg' => '交易密码错误！',
                'data' => '',
            ]);
        }
        $wallet = Wallets::where('wallet_user_id', $uid)->first();
        //检查钱包有没有
        foreach ($need_cards as $k => $v) {
            if ($wallet[$k] < 1) {
                return json([
                    'code' => 0,
                    'msg' => '没有卡片',
                    'data' => $k
                ]);
            }
        }
        //合成卡片-加U蛋
        //减去卡片
        $update_db = [];
        foreach ($need_cards as $k => $v) {
            $update_db[$k] = $wallet[$k] - 1;  //卡片减1
        }
        $update_db[$album_type] = $wallet[$album_type] + 1; //相册加1
        //加U蛋
        $get_eggs_name = $this->album_get_eggs($album_type);
        $update_db['held_eggs'] = ChickenCards::where('id', 2)->value($get_eggs_name) + $wallet['held_eggs'];

        //添加卡片记录
        CardsDB::insertGetId([
            'uid' => $uid,
            'card' => $album_type,
            'count' => 1,
            'type' => '使用卡片合成相册',
            'yu_e' => $this->cardsYue($uid),
            'created_at' => Carbon::now()->toDateTimeString()
        ]);
        //添加U蛋记录
        EggsDB::insertGetId([
            'uid' => $uid,
            'count' => ChickenCards::where('id', 2)->value($get_eggs_name),
            'type' => '合成相册奖励',
            'yu_e' => $update_db['held_eggs'],
            'created_at' => Carbon::now()->toDateTimeString()
        ]);

        $res = Wallets::where('wallet_user_id', $uid)->update($update_db);
        return json([
            'code' => 2,
            'msg' => '合成成功！',
            'data' => $res,
        ]);
    }

    /**
     * 转赠U蛋卡片
     */
    function giftEgg(Request $request)
    {
        $type = $request->post('type');
        $count = $request->post('count');
        $card_name = $request->post('card_name');
        $receiver_id = $request->post('receiver_id');
        $p = $request->post('p');
        $total = $request->post('total');

        $uid = $request->uid;
        //交易密码
        $trade_password = $request->post('trade_password');
        $trade_password_db = UserDB::where('uid', $uid)->value('trade_password');
        //校验密码
        if (!$this->verifyTradePwd($trade_password, $trade_password_db)) {
            return json([
                'code' => 0,
                'msg' => '交易密码错误！',
                'data' => '',
            ]);
        }
        if ($uid == $receiver_id) {
            return json(['code' => 4,
                'msg' => '自己不能赠送给自己！',
                'data' => '']);
        }

        //判断赠与的人是否存在
        $receiver_id_exists = Wallets::where('wallet_user_id',$receiver_id)->doesntExist();
        if($receiver_id_exists){
            return json(['code' => 4,
                'msg' => '赠予用户不存在，请重新输入！',
                'data' => '']);
        }


        $wallet = Wallets::where('wallet_user_id',  $uid)->first();
        //转增记录
        $gift_r = [
            'giver_id' => $uid,
            'receiver_id' => $receiver_id,
            'gift_type' => $type,
            'card_name' => $card_name,
            'egg_number' => $count,
            'created_at' => Carbon::now()->toDateTimeString()
        ];
        //计算剩余卡片
        $req = [];
        $req2 = [];
        //查看钱包有没有
        if ($type == 'eggs') {
            if ($wallet['held_eggs'] < $total) {
                return json(['code' => 4,
                    'msg' => 'U蛋不够！',
                    'data' => '']);
            } else {
                $req['held_eggs'] = $wallet['held_eggs'] - $total;
                $req2['held_eggs'] = Wallets::where('wallet_user_id', $receiver_id)->value('held_eggs') + $count;
                Wallets::where('wallet_user_id', $uid)->update($req);
                Wallets::where('wallet_user_id', $receiver_id)->update($req2);
                GiftEggs::insertGetId($gift_r);
                //添加U蛋记录-自己的
                EggsDB::insertGetId([
                    'uid' => $uid,
                    'count' => $count,
                    'type' => '赠送给别人U蛋',
                    'yu_e' => $req['held_eggs'],
                    'p'=>$p,
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);
                //添加U蛋记录-赠送别人
                EggsDB::insertGetId([
                    'uid' => $receiver_id,
                    'count' => $count,
                    'type' => '别人赠送的U蛋',
                    'yu_e' => $req2['held_eggs'],
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);
            }
        } else {
            if ($wallet[$card_name] < $count) {
                return json(['code' => 4,
                    'msg' => '卡片不够！',
                    'data' => '']);
            } else {
                $req[$card_name] = $wallet[$card_name] - $count;
                $req2[$card_name] = Wallets::where('wallet_user_id', $receiver_id)->value($card_name) + $count;
                Wallets::where('wallet_user_id', $uid)->update($req);
                Wallets::where('wallet_user_id', $receiver_id)->update($req2);
                GiftEggs::insertGetId($gift_r);
                //添加卡片记录-自己的
                CardsDB::insertGetId([
                    'uid' => $uid,
                    'card' => $card_name,
                    'count' => $count,
                    'type' => '赠送给别人的卡片',
                    'yu_e' => $this->cardsYue($uid),
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);
                //添加卡片记录-赠送别人的
                CardsDB::insertGetId([
                    'uid' => $receiver_id,
                    'card' => $card_name,
                    'count' => $count,
                    'type' => '别人赠送的卡片',
                    'yu_e' => $this->cardsYue($receiver_id),
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);
            }
        }

        return json([
            'code' => 2,
            'msg' => '转赠成功！',
            'data' => '',
        ]);
    }

    /**
     * @param Request $request
     * @return \support\Response
     * 查询转赠记录
     */
    function giftEggList(Request $request)
    {
        $uid = $request->uid;
        $res = GiftEggs::where('giver_id', $uid)->orWhere('receiver_id', $uid)->orderBy('id', 'desc')
            ->paginate(10);
        return json([
            'code' => 2,
            'msg' => '查询成功！',
            'data' => $res,
        ]);
    }

    //查询U蛋情况
    function getUseCardInfo(Request $request)
    {
        $uid = $request->uid;
        //已取出的U蛋
        //持续产出的U蛋
        //可取出的U蛋 记录中已经产生-已取出+利息产生的
        $yiyou_eggs = UserUseCards::where('user_id', $uid)->sum('done_eggs');
        $yiqu_eggs = Wallets::where('wallet_user_id', $uid)->value('quchu_eggs');
        $lixi_eggs = Wallets::where('wallet_user_id', $uid)->value('interest_eggs');
        $res['all_eggs'] = $yiyou_eggs - $yiqu_eggs + $lixi_eggs;      //可取出U蛋数
        $res['done_eggs'] = $yiyou_eggs;      //已经产出U蛋数
        $res['card_count'] = UserUseCards::where('user_id', $uid)->where('is_del', 0)->sum('card_count');
        $every_day_eggs = UserUseCards::where('user_id', $uid)->where('is_del', 0)->sum('every_day_eggs');
        $res['every_day_eggs'] = number_format($every_day_eggs, 6);
        $res['get_eggs'] = UserUseCards::where('user_id', $uid)->where('is_del', 0)->sum('get_eggs');
        //获取利息
        $res['interest'] = ChickenCards::where('id', 2)->value('interest');
        return json([
            'code' => 2,
            'msg' => '查询成功！',
            'data' => $res,
        ]);
    }


    /**
     * @param Request $request
     * @param Wallets $DB
     * @return \support\Response
     * 手动充值
     */
    public function addMoney(Request $request, Wallets $DB)
    {
        //充值对象
        $mail = $request->post('mail');
        //充值金额
        $count = $request->post('count');
        //获取充值钱包信息
        $cash_db = $DB->where('email', $mail)->value('cash');
        if($cash_db==null){
            return json([
                'code' => 0,
                'msg' => '',
                'data' => '账户不存在',
            ]);
        }else{
            //充值
            $DB->where('email', $mail)->update(
                [
                    'cash' => $cash_db+floatval($count),
                    'updated_at' => Carbon::now()->toDateTimeString()
                ]
            );
            //记录充值
            $uid = $DB->where('email', $mail)->value('wallet_user_id');
            //添加余额记录
            YueDB::insertGetId([
                'uid' => $uid,
                'count' => $count,
                'type' => '后台充值',
                'yu_e' =>  $cash_db+floatval($count),
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
        }
        return json([
            'code' => 2,
            'msg' => '充值成功！',
            'data' => '',
        ]);

    }



    public function queryData(Request $request)
    {
        $date = $request->get('date');
        return json([
            'code' => 2,
            'msg' => '',
            'data' => $date,
        ]);
    }


}
